#include "I18nStringsBundle.h"
#include "I18n.h"
#include <iostream>
#include <dirent.h>
#include <stdio.h>
#include <string.h>

namespace phnq
{
	namespace phnqlets
	{
		/*	The dir argument is assumed to be the path to a folder that contains
		*	folders representing locales, in which strings.xml files may be
		*	found.  So, the expected folder structure is would be...
		*	
		*	dir
		*	 + en
		*       - string.xml
		*	 + en_US
		*       - string.xml
		*	 + fr
		*       - string.xml
		*	 + it
		*       - string.xml
		*/
		I18nStringsBundle::I18nStringsBundle(string dir)
		{
			this->dir = dir;
			this->keys = NULL;
			
			DIR *d = opendir(dir.c_str());
			if(d)
			{
				struct dirent *pent;
				while(pent = readdir(d))
				{
					if(strcmp(pent->d_name, ".") && strcmp(pent->d_name, ".."))
					{
						string localeName(pent->d_name);
						
						string stringsFilePath = dir + "/" + localeName + "/strings.xml";
						
						FILE *f = fopen(stringsFilePath.c_str(), "r");
						if(f)
						{
							stringsByLocale[localeName] = new I18nStrings(stringsFilePath);
							
							fclose(f);
						}
					}
				}
				closedir(d);
			}
		}

		I18nStringsBundle::~I18nStringsBundle()
		{
			if(this->keys)
				delete this->keys;
		}

		set<string>* I18nStringsBundle::getAllKeys()
		{
			if(!this->keys)
			{
				this->keys = new set<string>();
				
				string locale = I18n::getCurrentLocale();

				size_t i = locale.length();
				do
				{
					locale = locale.substr(0, i);
					map<string,I18nStrings*>::iterator it = this->stringsByLocale.find(locale);
					if(it != this->stringsByLocale.end())
					{
						I18nStrings *strings = it->second;
						set<string> theKeys = strings->getAllKeys();
						
						for(set<string>::iterator it=theKeys.begin(); it!=theKeys.end(); it++)
						{
							this->keys->insert(*it);
						}
					}
				}
				while((i=locale.find_last_of("-_")) != string::npos);
			}
			
			return this->keys;
		}
		
		string* I18nStringsBundle::getString(string key)
		{
			string locale = I18n::getCurrentLocale();
			
			size_t i = locale.length();
			do
			{
				locale = locale.substr(0, i);
				map<string,I18nStrings*>::iterator it = this->stringsByLocale.find(locale);
				if(it != this->stringsByLocale.end())
				{
					I18nStrings *strings = it->second;
					if(strings->containsKey(key))
					{
						return strings->get(key);
					}
				}
			}
			while((i=locale.find_last_of("-_")) != string::npos);
			
			return NULL;
		}
	}
}
